package com.arui.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.arui.yygh.cmn.listener.DictListener;
import com.arui.yygh.cmn.mapper.DictMapper;
import com.arui.yygh.cmn.service.DictService;
import com.arui.yygh.model.cmn.Dict;
import com.arui.yygh.model.hosp.HospitalSet;
import com.arui.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Override
    @Cacheable(value = "dict",keyGenerator="keyGenerator")//第二次查从缓存中查，第一次查完后放入缓存中
    public List<Dict> findChildData(long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        //向集合中的每个对象设置hashChildren
        for (Dict dict:dicts) {
            dict.setHasChildren(this.isChildren(dict.getId()));
        }
        return dicts;
    }
    //导出数据字典接口
    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        List<Dict> dicts = baseMapper.selectList(null);
        //Dict -- DictEeVo
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        for (Dict dict:dicts) {
            DictEeVo dictEeVo = new DictEeVo();
//            dictEeVo.setDictCode(dict.getDictCode());
//            dictEeVo.setId(dict.getId());
//            dictEeVo.setValue(dict.getValue());
//            dictEeVo.setParentId(dict.getParentId());
//            dictEeVo.setName(dict.getName());
            BeanUtils.copyProperties(dict,dictEeVo);
            dictEeVoList.add(dictEeVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //根据dictCode和value查询
    @Override
    public String getDictName(String dictCode, String value) {
        if ("".equals(dictCode)){
            //直接根据value查
            QueryWrapper<Dict> wrapper = new QueryWrapper();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else{
            //根据dictCode和value查询
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parentId = codeDict.getId();
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_Id", parentId)
                    .eq("value", value));

            return finalDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.getDictByDictCode(dictCode);
        Long id = dict.getId();
        List<Dict> list = this.findChildData(id);
        return list;

    }

    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    //判断id下面是否有子数据
    private boolean isChildren(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
